<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Requests_Response;

/**
 * App\YaoUserPostLog
 *
 * @property int $id
 * @property string $request_url 请求地址
 * @property string|null $payload 请求参数
 * @property string|null $response 返回结果
 * @property int $http_code http请求状态码
 * @property int $is_success 操作是否成功
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog whereHttpCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog whereIsSuccess($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog wherePayload($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog whereRequestUrl($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog whereResponse($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\YaoUserPostLog whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class YaoUserPostLog extends Model
{
    public static function addLog($url,$payload,$response){
        try {
            /** @var Requests_Response $response */
            $record                 = new self();
            $record->request_url    = $url ?? '';
            $record->payload        = $payload ? json_encode($payload) : '';
            $record->http_code      = $response->getStatusCode() ?? 0;
            if ($response->getStatusCode() == 200){
                $record->response   = $response->getBody() ?? '';
            }
            if ($record->response){
                $data = json_decode($record->response);
                if (isset($data->code) && $data->code == 200){
                    $record->is_success = 1;
                } else {
                    $record->is_success = 0;
                }
            }
            $record->save();
            return 1;
        } catch (\Exception $exception){
            \Log::error('YaoUserPostLog->addLog()ERROR_MESSAGE:'.$exception->getMessage());
            \Log::error('YaoUserPostLog->addLog()ERROR_Trace:'.$exception->getTraceAsString());
            return 0;
        }
    }
}
